<?php
// Assumes $conn (database connection) and $_SESSION['user_id'] are available.
// NOTE: Ensure 'config/db_connection.php' is properly included in admin_dashboard.php 
// and $conn is a valid mysqli connection object.
// ** Uncomment session_start() and include in a real environment **
// session_start(); 
// include 'config/db_connection.php'; 

// --- START: USER AUTHENTICATION & VARIABLE SETUP ---
// Fallback if session is not yet started or user not logged in (FOR DEMO/TESTING ONLY)
if (!isset($_SESSION['user_id'])) {
    // Simulating logged-in user data. Change role to 'Admin' to test approval flow.
    $_SESSION['user_id'] = 5001; 
    $_SESSION['username'] = 'Saiyeda Marzia'; 
    $_SESSION['role'] = 'SOC Engineer'; // Change to 'Admin' to test approval/rejection
}

$status_message = '';
$generated_content = null;
$user_authenticated = isset($_SESSION['user_id']);
$is_admin = (isset($_SESSION['role']) && $_SESSION['role'] == 'Admin'); // Check for Admin role

if ($user_authenticated) {
    $user_id = $_SESSION['user_id'];
    $username = $_SESSION['username'] ?? 'Employee Name'; 
    $user_role = $_SESSION['role'] ?? 'Unspecified Role'; 
} else {
    $status_message = "<div class='alert alert-error'>User not authenticated. Please log in to view this page.</div>";
    $username = 'Guest';
    $user_role = 'N/A';
}

// Data from form submission (used for sticky fields)
$application_date = $_POST['application_date'] ?? date('Y-m-d');
$application_body = $_POST['application_body'] ?? '';


// --- Fixed Letterhead Components ---
$company_name = "Cyberlog Ltd.";
$company_address_short = "1/6, Block: New- C, Mirpur-1, Dhaka-1216";
$company_email = "info@cyberlog.com.bd";
$company_website = "www.cyberlog.com.bd";

$recipient_name = "Hridoy Mustofa";
$recipient_title = "Founder & CEO";
$recipient_details = "Cyberlog Ltd.<br>1/6, Block: New- C, Mirpur-1,<br>Dhaka-1216, Bangladesh";


// --- ADMIN ACTION HANDLER (Approve/Reject) ---
if ($user_authenticated && $is_admin && isset($_GET['action']) && isset($_GET['app_id']) && is_numeric($_GET['app_id'])) {
    $app_id = (int)$_GET['app_id'];
    $action = $_GET['action'];
    $new_status = '';

    if ($action == 'approve') {
        $new_status = 'Approved';
    } elseif ($action == 'reject') {
        $new_status = 'Rejected';
    }

    if ($new_status && isset($conn)) {
        // Update the status in the database
        $sql_update = "UPDATE leave_applications SET status = ?, reviewed_by = ? WHERE id = ? AND status = 'Pending'";
        if ($stmt_update = $conn->prepare($sql_update)) {
            $stmt_update->bind_param("ssi", $new_status, $username, $app_id);
            if ($stmt_update->execute() && $stmt_update->affected_rows > 0) {
                $status_message = "<div class='alert alert-success'>Application ID **{$app_id}** successfully marked as **{$new_status}**.</div>";
            } elseif ($stmt_update->affected_rows === 0) {
                 $status_message = "<div class='alert alert-error'>Application ID **{$app_id}** was not updated (might have already been reviewed).</div>";
            } else {
                $status_message = "<div class='alert alert-error'>Database Error: Could not update status.</div>";
            }
            $stmt_update->close();
        }
    }
    // Redirect to the viewing page after action to prevent re-submission on refresh
    header("Location: admin_dashboard.php?page=leave_application&view_app_id={$app_id}");
    exit;
}


// --- FUNCTION: Builds the Leave Application HTML (Unchanged structure) ---
function get_leave_application_html(
    $app_id, 
    $app_date, 
    $app_body, 
    $user_name, 
    $user_role,
    $recipient_name,
    $recipient_title,
    $recipient_details,
    $status = 'Pending' 
) {
    global $company_name, $company_address_short, $company_email, $company_website;
    
    // NOTE: This HTML is optimized for clean printing/PDF generation.
    $html = "
    <div class='letter-page'>
        <div class='header-top'>
            <div class='logo-text'>Cyberlog</div>
            <div class='contact-info'>
                <p>{$company_address_short} <span style='color: #E74C3C;'>&#x1F4CD;</span></p>
                <p>{$company_email} <span style='color: #E74C3C;'>&#x2709;</span></p>
                <p>{$company_website} <span style='color: #E74C3C;'>&#x1F310;</span></p>
            </div>
        </div>
        <div style='border-bottom: 2px solid #0056b3; width: 100%; margin-top: -10px;'>&nbsp;</div>
        
        <div style='margin-top: 20px; font-size: 14px;'>
            <p><span class='plain-text'>Date:</span> <span style='border-bottom: 1px dashed #333;'>".date('F j, Y', strtotime($app_date))."</span></p>
        </div>

        <div class='plain-box' style='width: 300px; padding: 10px; margin-top: 15px;'>
            <p style='margin: 0;'>To,</p>
            <p style='margin: 0;'>{$recipient_name}</p>
            <p style='margin: 0;'>{$recipient_title}</p>
            <p style='margin: 0;'>{$recipient_details}</p>
        </div>

        <p class='plain-box' style='width: 250px; margin-top: 20px;'>Subject: Request for Leave.</p>
        <p class='plain-box' style='width: 150px;'>Dear Sir,</p>
        
        <div class='app-body-content-plain' style='padding: 15px; margin-top: 15px; min-height: 250px;'>
            ".nl2br(htmlspecialchars($app_body))."
        </div>
        
        <div class='plain-box' style='width: 250px; margin-top: 40px; padding: 15px;'>
            <p style='margin: 0;'>Sincerely,</p>
            <p style='text-decoration: underline; margin: 5px 0 2px 0;'>{$user_name}</p>
            <p style='margin: 0;'>{$user_name}</p>
            <p style='margin: 0;'>{$user_role},</p>
            <p style='margin: 0;'>{$company_name}</p>
        </div>

        <div style='width: 100%; margin-top: 40px; border-bottom: 10px solid #0056b3;'>&nbsp;</div>
        <p style='text-align: center; font-size: 10px; color: #888;'>Application Status: <span class=\"status-{$status}\">{$status}</span></p>
    </div>
    ";
    return $html;
}


// --- Logic to View a Specific Leave Application ---
$current_app_status = '';
$current_app_id = null;

if ($user_authenticated && isset($_GET['view_app_id']) && is_numeric($_GET['view_app_id'])) {
    $view_id = (int)$_GET['view_app_id'];
    $current_app_id = $view_id; // Store ID for admin buttons

    // Admin should be able to view ANY application, employees only their own.
    $sql_where = $is_admin ? "id = ?" : "id = ? AND created_by = ?";
    $sql_main = "SELECT * FROM leave_applications WHERE {$sql_where}";
    
    if (isset($conn) && $stmt_main = $conn->prepare($sql_main)) {
        if ($is_admin) {
             $stmt_main->bind_param("i", $view_id);
        } else {
             $stmt_main->bind_param("ii", $view_id, $user_id);
        }

        $stmt_main->execute();
        $result_main = $stmt_main->get_result();
        $app_record = $result_main->fetch_assoc();
        $stmt_main->close();

        if ($app_record) {
            $current_app_status = $app_record['status']; // Store status for button logic

            // When Admin views an app, use the original applicant's details for the signature block
            $applicant_username = $app_record['username'];
            $applicant_role = $app_record['role'];
            
            $generated_content = get_leave_application_html(
                $app_record['id'], 
                $app_record['application_date'], 
                $app_record['application_body'], 
                $applicant_username, 
                $applicant_role,
                $recipient_name,
                $recipient_title,
                $recipient_details,
                $current_app_status
            );
            
            $status_message = "<div class='alert alert-info'>Viewing Application ID: **{$app_record['id']}** (Status: {$current_app_status}) from ".date('M j, Y', strtotime($app_record['application_date']))."</div>";
            
            // Do NOT update sticky fields when viewing history
            // $application_date = $app_record['application_date'];
            // $application_body = $app_record['application_body'];
            
        } else {
             $status_message = "<div class='alert alert-error'>Leave application not found or you are unauthorized to view it.</div>";
        }
    } else if ($user_authenticated) {
        $status_message = "<div class='alert alert-error'>Database connection required to view records.</div>";
    }
}


// --- Logic to Handle Form Submission (Submit and Save as Pending) ---
if ($user_authenticated && $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit_application'])) { 
    
    // 1. Sanitize & Prepare Inputs
    $application_date = isset($conn) ? $conn->real_escape_string($_POST['application_date'] ?? date('Y-m-d')) : ($_POST['application_date'] ?? date('Y-m-d'));
    $application_body = isset($conn) ? $conn->real_escape_string($_POST['application_body'] ?? '') : ($_POST['application_body'] ?? '');
    
    if (empty($application_date) || empty($application_body)) {
        $status_message = "<div class='alert alert-error'>Both the Date and the Application Body fields are required.</div>";
    } else {
        // --- Database Logic: Save to DB with 'Pending' status ---
        $initial_status = 'Pending';
        if (isset($conn)) {
            // Updated SQL to include status and role
            $sql_main = "INSERT INTO leave_applications (application_date, application_body, created_by, username, role, status) 
                         VALUES (?, ?, ?, ?, ?, ?)";
            
            if ($stmt_main = $conn->prepare($sql_main)) {
                $stmt_main->bind_param("sissss", $application_date, $application_body, $user_id, $username, $user_role, $initial_status);
                
                if ($stmt_main->execute()) {
                    $last_id = $stmt_main->insert_id;
                    $status_message = "<div class='alert alert-success'>Leave Application ID **{$last_id}** submitted successfully and is now **Pending** review by the admin.</div>";

                    // Generate HTML Content for the Draft Viewer
                    $generated_content = get_leave_application_html(
                        $last_id, 
                        $application_date, 
                        $application_body, 
                        $username, 
                        $user_role,
                        $recipient_name,
                        $recipient_title,
                        $recipient_details,
                        $initial_status
                    );
                    // Clear fields after successful submission
                    $application_date = date('Y-m-d');
                    $application_body = '';
                    
                } else {
                    $status_message = "<div class='alert alert-error'>Database error: " . $stmt_main->error . "</div>";
                }
                $stmt_main->close();
            } else {
                $status_message = "<div class='alert alert-error'>Database preparation error: " . $conn->error . "</div>";
            }
        } else {
            // No database connection available (development/testing environment)
            $status_message = "<div class='alert alert-success'>Leave Application submitted successfully (DB save skipped in demo mode). Status: **Pending**.</div>";
            
            // Generate HTML Content for the Draft Viewer
            $generated_content = get_leave_application_html(
                'DRAFT', 
                $application_date, 
                $application_body, 
                $username, 
                $user_role,
                $recipient_name,
                $recipient_title,
                $recipient_details,
                $initial_status
            );
        }
    }
}
?>

<style>
    /* General Styling */
    .form-card { background: white; padding: 25px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); margin-bottom: 20px; }
    h3 { color: #0056b3; border-bottom: 1px solid #eee; padding-bottom: 10px; margin-top: 0; }
    
    /* Alerts (From expense.php) */
    .alert-error { background-color: #fbecec; border: 1px solid #e74c3c; color: #e74c3c; padding: 10px; border-radius: 5px; margin-bottom: 10px; }
    .alert-success { background-color: #e8f5e9; border: 1px solid #2ecc71; color: #2ecc71; padding: 10px; border-radius: 5px; margin-bottom: 10px; }
    .alert-info { background-color: #ebf5fb; border: 1px solid #3498db; color: #3498db; padding: 10px; border-radius: 5px; margin-bottom: 10px; }

    /* --- KEY CHANGES: REMOVING BOX COLORS AND BOLDNESS --- */
    input[type="date"], textarea { 
        width: 100%; 
        padding: 10px; 
        border: 1px solid #ccc; /* Generic light border for input fields */
        box-sizing: border-box; 
        margin-top: 5px; 
        font-size: 16px; 
        margin-bottom: 15px; 
    }
    textarea { min-height: 200px; resize: vertical; }

    /* Removes green background, border, and bold from fixed text elements */
    .fixed-green-box { 
        background-color: white !important; /* Force white background */
        border: none !important; /* Remove border */
        padding: 0; /* Tighten padding */
        margin-bottom: 5px; 
        display: block; 
        font-weight: normal !important; /* Remove bold */
    }
    .label-group { margin-bottom: 15px; }

    /* Button Group (From expense.php) */
    .button-group-aligned { margin-top: 30px; display: flex; justify-content: space-between; align-items: center; width: 100%; }
    .right-aligned-buttons { display: flex; gap: 10px; }
    .action-button { min-width: 150px; text-align: center; padding: 12px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; text-decoration: none; font-weight: bold; transition: background-color 0.3s; display: inline-block; }
    .primary-btn { background-color: #5d9cec; color: white; }
    .warning-btn { background-color: #ffcc66; color: #333; }
    .secondary-btn { background-color: #aab8c2; color: white; }
    .secondary-btn:hover { background-color: #8c97a1; }
    .download-btn { background-color: #e74c3c; color: white; } /* Keeping for download button on the preview */
    .approve-btn { background-color: #2ecc71; color: white; }
    .reject-btn { background-color: #e74c3c; color: white; }

    /* Table Styles (From expense.php) */
    .app-history-table { width: 100%; border-collapse: collapse; margin-top: 15px; }
    .app-history-table th, .app-history-table td { border: 1px solid #ccc; padding: 8px; text-align: left; font-size: 14px; }
    .app-history-table th { background-color: #f2f2f2; font-weight: bold; }

    /* Status Coloring */
    .status-Pending { color: orange; font-weight: bold; }
    .status-Approved { color: green; font-weight: bold; }
    .status-Rejected { color: red; font-weight: bold; }

    /* Letterhead Preview Styles (Customized from expense.php) */
    .letter-page { padding: 30px; background: white; border: 1px solid #ddd; box-shadow: 0 0 10px rgba(0,0,0,0.05); min-height: 900px; box-sizing: border-box; }
    .header-top { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; }
    .logo-text { font-size: 30px; font-weight: bold; color: #0056b3; }
    .contact-info { text-align: right; font-size: 12px; color: #555; }
    .contact-info p { margin: 0; }
    
    /* Print Styles (Crucial for PDF download look) */
    @media print {
        body > *:not(.print-container-wrapper) { display: none; }
        .print-container-wrapper { display: block !important; width: 100%; margin: 0; padding: 0; }
        .letter-page { box-shadow: none; border: none; min-height: auto; position: relative; }
        
        /* Ensure print output is plain */
        .plain-box { background-color: white !important; border: none !important; font-weight: normal !important; }
        .app-body-content-plain { border: none !important; }

        /* Final print control */
        @page { size: A4; margin: 0.5in; }
        * { -webkit-print-color-adjust: exact !important; color-adjust: exact !important; }
    }
</style>

<div class="form-card">
    <h3>New Leave Application (Logged in as: <?php echo htmlspecialchars($username); ?>)</h3>
    <?php echo $status_message; ?>

    <form action="admin_dashboard.php?page=leave_application" method="post" id="leaveApplicationForm">
        
        <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($user_id); ?>">
        <input type="hidden" name="username" value="<?php echo htmlspecialchars($username); ?>">
        <input type="hidden" name="user_role" value="<?php echo htmlspecialchars($user_role); ?>">

        <div class="label-group">
            <label for="application_date" class="fixed-green-box" style="width: 100px; padding: 0 0 5px 0;">Date</label>
            <input type="date" name="application_date" id="application_date" required 
                   value="<?php echo htmlspecialchars($application_date); ?>">
        </div>

        <div class="fixed-green-box" style="width: 300px;">
            <p style="margin: 0;">To,</p>
            <p style="margin: 0;"><?php echo $recipient_name; ?></p>
            <p style="margin: 0;"><?php echo $recipient_title; ?></p>
            <p style="margin: 0;"><?php echo $recipient_details; ?></p>
        </div>
        <br/>
        
        <p class="fixed-green-box" style="width: 350px;">Subject: Request for Leave.</p>
        <br/>
        
        <p class="fixed-green-box" style="width: 150px;">Dear Sir,</p>
        
        <div class="label-group">
            <textarea name="application_body" id="application_body" required 
                      placeholder="Enter the body of your leave application here (e.g., reason, start date, end date, total days)."><?php echo htmlspecialchars($application_body); ?></textarea>
        </div>

        <div class="fixed-green-box" style="width: 300px;">
            <p style="margin: 0;">Sincerely,</p>
            <p style="margin: 0;"><?php echo htmlspecialchars($username); ?></p>
            <p style="margin: 0;"><?php echo htmlspecialchars($user_role); ?></p>
            <p style="margin: 0;">Cyberlog Ltd.</p>
        </div>
        
        <div class="button-group-aligned">
            <button type="submit" name="submit_application" class="action-button primary-btn">
                Submit
            </button>
            
            <div class="right-aligned-buttons">
                <button type="reset" class="action-button warning-btn">
                    Reset Form
                </button>
                <a href="admin_dashboard.php" class="action-button secondary-btn">
                    Cancel
                </a>
            </div>
        </div>
    </form>
</div>

<?php if (isset($generated_content)): ?>
<div class="form-card print-container-wrapper" style="margin-top: 20px;">
    <h3>Leave Application Draft Preview</h3>
    
    <div style="text-align: center; margin-bottom: 20px;">
        <?php if ($is_admin && $current_app_status == 'Pending' && $current_app_id): ?>
            <a href="admin_dashboard.php?page=leave_application&action=approve&app_id=<?php echo $current_app_id; ?>" 
               class="action-button approve-btn" 
               onclick="return confirm('Are you sure you want to APPROVE this application?');">
                Approve
            </a>
            <a href="admin_dashboard.php?page=leave_application&action=reject&app_id=<?php echo $current_app_id; ?>" 
               class="action-button reject-btn" style="margin-left: 10px;"
               onclick="return confirm('Are you sure you want to REJECT this application?');">
                Reject
            </a>
        <?php elseif ($is_admin && $current_app_status != 'Pending'): ?>
            <p class="alert alert-info">Application status is **<?php echo htmlspecialchars($current_app_status); ?>**. No further action required.</p>
        <?php endif; ?>
        
        <button onclick="downloadPdf('<?php echo 'Leave_Application_' . date('Ymd'); ?>')" 
                class="action-button download-btn" style="margin-left: 10px;">
            <i class="fas fa-file-pdf"></i> Download/Print
        </button>
        <a href="admin_dashboard.php?page=leave_application" 
                class="action-button primary-btn" style="margin-left: 10px;">
            + Create New
        </a>
    </div>
    
    <div id="print_area" class="print-container">
        <?php echo $generated_content; ?>
    </div>
</div>
<?php endif; ?>

<div class="form-card" style="margin-top: 40px;">
    <h3>Saved Leave Application History</h3>
    
    <?php
    // Fetch applications: Admin sees all, Employee sees only their own.
    $app_history = [];
    $sql_history_fields = "id, application_date, username, created_at, status";
    
    if (isset($conn) && $user_authenticated) {
        if ($is_admin) {
             // Admin sees all applications
             $sql_history = "SELECT {$sql_history_fields} FROM leave_applications ORDER BY created_at DESC LIMIT 10";
             $stmt_history = $conn->prepare($sql_history);
             $stmt_history_ready = $stmt_history;
        } else {
             // Employee sees only their own
             $sql_history = "SELECT {$sql_history_fields} FROM leave_applications WHERE created_by = ? ORDER BY created_at DESC LIMIT 10";
             $stmt_history = $conn->prepare($sql_history);
             if ($stmt_history) {
                $stmt_history->bind_param("i", $user_id);
                $stmt_history_ready = $stmt_history;
             } else {
                 $stmt_history_ready = false;
             }
        }
        
        if ($stmt_history_ready) {
            $stmt_history_ready->execute();
            $result_history = $stmt_history_ready->get_result();
            while ($row = $result_history->fetch_assoc()) {
                $app_history[] = $row;
            }
            $stmt_history_ready->close();
        }
    }
    
    if (empty($app_history)):
    ?>
        <div class="alert alert-info">No leave applications found for your account yet.</div>
    <?php else: ?>
        <table class="app-history-table">
            <thead>
                <tr>
                    <th style="width: 5%;">ID</th>
                    <th style="width: 15%;">Application Date</th>
                    <th style="width: 20%;">Applied By</th>
                    <th style="width: 15%;">Status</th> 
                    <th style="width: 30%;">Submitted On</th>
                    <th style="width: 15%; text-align: center;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($app_history as $app): ?>
                <tr>
                    <td><?php echo htmlspecialchars($app['id']); ?></td>
                    <td><?php echo date('M d, Y', strtotime($app['application_date'])); ?></td>
                    <td><?php echo htmlspecialchars($app['username']); ?></td>
                    <td><span class="status-<?php echo htmlspecialchars($app['status']); ?>"><?php echo htmlspecialchars($app['status']); ?></span></td>
                    <td><?php echo date('M d, Y h:i A', strtotime($app['created_at'])); ?></td>
                    <td style="text-align: center;">
                        <a href="admin_dashboard.php?page=leave_application&view_app_id=<?php echo $app['id']; ?>" 
                           class="action-button" style="background-color: #3498db; padding: 5px 10px; color: white; text-decoration: none; border-radius: 3px; font-size: 0.9em;">
                            View
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<script>
    // --- PDF-like Download Function using window.print() (Unchanged) ---
    function downloadPdf(filename) {
        const printContent = document.getElementById('print_area').innerHTML;
        const printWindow = window.open('', '', 'height=600,width=800');
        printWindow.document.write('<html><head><title>' + filename + '</title>');
        
        // Include necessary CSS styles for a clean print output
        printWindow.document.write(`
            <style>
                body { font-family: Arial, sans-serif; margin: 0; padding: 0; }
                
                /* Copy paste the essential print styles from the main stylesheet */
                .letter-page {
                    position: relative;
                    padding: 30px; 
                    background: white;
                    box-sizing: border-box;
                    width: 100%;
                }
                .header-top { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; }
                .logo-text { font-size: 30px; font-weight: bold; color: #0056b3; }
                .contact-info { text-align: right; font-size: 12px; color: #555; }
                .contact-info p { margin: 0; }
                
                /* Ensure print output is plain (white background, no border, no bold) */
                .plain-box { background-color: white !important; border: none !important; font-weight: normal !important; }
                .app-body-content-plain { border: none !important; }

                /* Final print control */
                @page { size: A4; margin: 0.5in; }
                * { -webkit-print-color-adjust: exact !important; color-adjust: exact !important; }
            </style>
        `);
        
        printWindow.document.write('</head><body>');
        printWindow.document.write(printContent);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        
        // Trigger the print dialog (which allows saving as PDF)
        printWindow.focus();
        printWindow.print();
        printWindow.close(); // Close the pop-up after print dialog is closed/canceled
    }

</script>